package com.haiertvbic.tvnow.pop;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.PopupWindow;

import com.haiertvbic.tvnow.R;
import com.haiertvbic.tvnow.TVNOWMainActivity;
import com.haiertvbic.tvnow.model.ScreenShot;
import com.haiertvbic.tvnow.util.SLog;
import com.haiertvbic.tvnow.widget.PipCache;
import com.haiertvbic.tvnow.widget.Rotate3DAnimation;

public class PipPop extends PopWindow {
	private Activity context;
	private View childView;
	private String checkCid = null;

	protected static final int SHOW_THE_PIP_POPWINDOW = 10000;
	private static final String TAG = "PipPop";
	// 判断gallery的显示
	private boolean galleryC = false;
	private PopupWindow pop;
	private Timer pip_tt;
	private Handler pipHandler;
	private boolean flag1 = true;
	private boolean flag2 = true;
	private boolean flag3 = true;
	private boolean burshShow1 = true;
	private boolean burshShow2 = true;
	private boolean burshShow3 = true;
	private static Map<String, String> isOne = new HashMap<String, String>();
	// 判断popwindow是否显示
	private Boolean isShowPopWindow = false;

	public PipPop(Activity context, String checkCid) {
		this.context = context;
		this.childView = TVNOWMainActivity.childView;
		this.checkCid = checkCid;
		galleryC = false;
	}

	@Override
	public void dismissPop() {
		isOne.clear();
		if (pop != null && pop.isShowing()) {
			pop.dismiss();
			pop = null;
		}
		if (pip_tt != null) {
			pip_tt.cancel();
			pip_tt = null;
		}
		galleryC = false;
		isShowPopWindow = false;
	}

	public boolean getPopState() {
		return galleryC;
	}

	@Override
	public void showPop() {
		final PIPHolder pip;
		synchronized (isShowPopWindow) {
			if (isShowPopWindow)
				return;
			isShowPopWindow = true;
			burshShow1 = true;
			burshShow2 = true;
			burshShow3 = true;
			pip = initPIP();
			PipCache.pipListMap = new HashMap<String, ArrayList<ScreenShot>>();
		}

		pipHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case SHOW_THE_PIP_POPWINDOW:
					ArrayList<Bitmap> bm_pip = null;
					bm_pip = (ArrayList<Bitmap>) msg.obj;
					String currentCid = checkCid;
					if (bm_pip != null) {
						if (currentCid.equalsIgnoreCase(String
								.valueOf(msg.arg1)) && isShowPopWindow) {
							fillPipPicData(pip, bm_pip);
						}
					}
					break;

				default:
					break;
				}
			}
		};
		pip_tt = new Timer();
		pip_tt.schedule(new TimerTask() {
			@Override
			public void run() {
				pipMove();
			}
		}, 0, 7000);

	}

	class PIPHolder {
		public ImageView channel_pop_iv1;
		public ImageView channel_pop_iv2;
		public ImageView channel_pop_iv3;
	}

	private PIPHolder initPIP() {
		PIPHolder pip = new PIPHolder();
		View connvert = LayoutInflater.from(context).inflate(
				R.layout.pop_channel, null);
		// ==========取控件==============
		pip.channel_pop_iv1 = (ImageView) connvert
				.findViewById(R.id.channel_pop_iv1);
		pip.channel_pop_iv2 = (ImageView) connvert
				.findViewById(R.id.channel_pop_iv2);
		pip.channel_pop_iv3 = (ImageView) connvert
				.findViewById(R.id.channel_pop_iv3);
		int[] arrayOfInt = new int[2];
		if (childView != null) {
			childView.getLocationInWindow(arrayOfInt);
			float pictureHeight = context.getResources().getDimension(
					R.dimen.picture_height);
			// 当条目被选中弹出popwindow
			pop = new PopupWindow(connvert, 320 * 2,
					(int) (pictureHeight + 0.5f));
			pop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
			pop.showAtLocation(childView, Gravity.LEFT | Gravity.TOP,
					arrayOfInt[0], arrayOfInt[1]);// 高度需要往上在调一点
			SLog.d(TAG, "arrayOfInt[0]===" + arrayOfInt[0]);
			SLog.d(TAG, "arrayOfInt[1]=======" + arrayOfInt[1]);
		}
		return pip;
	}

	private void pipMove() {
		ArrayList<Bitmap> bm_pips = null;
		int checkCidInt = Integer.valueOf(checkCid);
		String checkCid = checkCidInt + "";
		long currentTime = System.currentTimeMillis();
		ArrayList<ScreenShot> screenList = PipCache.getRealTimeShort(context,
				checkCid);
		long screenTime = System.currentTimeMillis() - currentTime;
		// 总时间-取图所花时间
		long delayed = 0;
		if (screenTime < 7000) {
			delayed = 7000 - screenTime;
		} else {
			delayed = 0;
		}
		if (screenList != null && screenList.size() > 0) {
			bm_pips = new ArrayList<Bitmap>();
			for (int i = 0; i < screenList.size(); i++) {
				bm_pips.add(screenList.get(i).getBm());
			}
		}
		if (bm_pips != null && bm_pips.size() > 0) {
			Message msg = Message.obtain();
			msg.what = SHOW_THE_PIP_POPWINDOW;
			msg.arg1 = checkCidInt;
			msg.obj = bm_pips;
			String currentCid = checkCid;
			if (checkCid.equalsIgnoreCase(currentCid) && isShowPopWindow) {
				if (isOne.containsKey(currentCid)
						&& isOne.get(currentCid) != null) {
					if (isOne.get(currentCid) == "1") {
						pipHandler.sendMessage(msg);
						isOne.put(checkCid, "2");
					} else if (isOne.get(currentCid) == "2") {
						delayed = delayed / 2;
						pipHandler.sendMessageDelayed(msg, delayed);
						isOne.put(checkCid, "3");
					} else {
						pipHandler.sendMessageDelayed(msg, delayed);
					}
				} else {
					pipHandler.sendMessage(msg);
					isOne.put(checkCid, "1");
				}
			}
		}
	}

	private void fillPipPicData(final PIPHolder pip, final ArrayList<Bitmap> bms) {
		int centerX = pip.channel_pop_iv1.getLayoutParams().width >> 1;
		int centerY = pip.channel_pop_iv1.getLayoutParams().height >> 1;
		if (bms.size() == 3) {
			flag1 = true;
			final Animation anim1 = new Rotate3DAnimation(centerX, centerY,
					Rotate3DAnimation.ROTATE_DECREASE);// true
			anim1.setAnimationListener(new AnimationListener() {
				@Override
				public void onAnimationStart(Animation animation) {
					if (burshShow1) {
						pip.channel_pop_iv1.setVisibility(View.VISIBLE);
					}
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationEnd(Animation animation) {
					pip.channel_pop_iv1.setVisibility(View.VISIBLE);
					burshShow1 = false;
					galleryC = true;
				}
			});
			pip.channel_pop_iv1.postDelayed(new Runnable() {
				@Override
				public void run() {
					((Rotate3DAnimation) anim1)
							.setInterpolatedTimeListener(new Rotate3DAnimation.InterpolatedTimeListener() {
								@Override
								public void interpolatedTime(
										float interpolatedTime) {
									if (burshShow1) {
										pip.channel_pop_iv1
												.setAlpha(interpolatedTime);
									} else {
										if (interpolatedTime <= 0.5) {
											pip.channel_pop_iv1
													.setAlpha((0.5f - interpolatedTime) / 0.5f);
										} else if (interpolatedTime > 0.5) {
											pip.channel_pop_iv1
													.setAlpha((interpolatedTime - 0.5f) / 0.5f);
										}
									}
									if (flag1 & interpolatedTime > 0.5f) {
										pip.channel_pop_iv1.setImageBitmap(bms
												.get(2));// 翻转后的新图
										flag1 = false;
									}
								}
							});
					pip.channel_pop_iv1.startAnimation(anim1);
				}
			}, 1000 * 2);

		}

		// ==========第二个动画======================================
		if (bms.size() > 2) {

			centerX = pip.channel_pop_iv2.getLayoutParams().width >> 1;
			centerY = pip.channel_pop_iv2.getLayoutParams().height >> 1;
			final Animation anim2 = new Rotate3DAnimation(centerX, centerY,
					Rotate3DAnimation.ROTATE_DECREASE);
			AnimationSet translate_rotate2 = new AnimationSet(true);
			int sreenWidth = context.getWindowManager().getDefaultDisplay()
					.getWidth();
			TranslateAnimation translate = new TranslateAnimation(sreenWidth,
					0, 0, 0);
			translate.setDuration(1000 * 2);
			anim2.setAnimationListener(new AnimationListener() {
				@Override
				public void onAnimationStart(Animation animation) {
					if (burshShow2)
						pip.channel_pop_iv2.setImageBitmap(bms.get(2));

				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationEnd(Animation animation) {
					pip.channel_pop_iv2.setVisibility(View.VISIBLE);
					burshShow2 = false;
				}
			});
			flag2 = true;
			((Rotate3DAnimation) anim2)
					.setInterpolatedTimeListener(new Rotate3DAnimation.InterpolatedTimeListener() {
						@Override
						public void interpolatedTime(float interpolatedTime) {
							if (burshShow2) {
								pip.channel_pop_iv2.setAlpha(interpolatedTime);
							} else {
								if (interpolatedTime <= 0.5) {
									pip.channel_pop_iv2
											.setAlpha((0.5f - interpolatedTime) / 0.5f);
								} else if (interpolatedTime > 0.5) {
									pip.channel_pop_iv2
											.setAlpha((interpolatedTime - 0.5f) / 0.5f);
								}
							}
							if (flag2 & interpolatedTime > 0.5f) {
								pip.channel_pop_iv2.setImageBitmap(bms.get(1));// 翻转后的新图
								flag2 = false;
							}
						}
					});
			Animation inanim = AnimationUtils.loadAnimation(context,
					R.anim.brush);
			translate_rotate2.addAnimation(inanim);
			translate_rotate2.addAnimation(translate);
			translate_rotate2.addAnimation(anim2);
			if (burshShow2) {
				pip.channel_pop_iv2.startAnimation(translate_rotate2);
			} else {
				pip.channel_pop_iv2.startAnimation(anim2);
			}
		}

		// ==========第三个动画======================================
		if (bms.size() > 2) {
			centerX = pip.channel_pop_iv3.getLayoutParams().width >> 1;
			centerY = pip.channel_pop_iv3.getLayoutParams().height >> 1;
			final Animation anim3 = new Rotate3DAnimation(centerX, centerY,
					Rotate3DAnimation.ROTATE_INCREASE);// false
			anim3.setAnimationListener(new AnimationListener() {
				@Override
				public void onAnimationStart(Animation animation) {
					if (burshShow3) {
						pip.channel_pop_iv3.setVisibility(View.VISIBLE);
					}
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationEnd(Animation animation) {
					pip.channel_pop_iv3.setVisibility(View.VISIBLE);
					burshShow3 = false;
				}
			});
			pip.channel_pop_iv3.postDelayed(new Runnable() {

				@Override
				public void run() {
					flag3 = true;
					anim3.setFillAfter(true);
					((Rotate3DAnimation) anim3)
							.setInterpolatedTimeListener(new Rotate3DAnimation.InterpolatedTimeListener() {
								@Override
								public void interpolatedTime(
										float interpolatedTime) {
									if (burshShow3) {
										pip.channel_pop_iv3
												.setAlpha(interpolatedTime);
									} else {
										if (interpolatedTime <= 0.5) {
											pip.channel_pop_iv3
													.setAlpha((0.5f - interpolatedTime) / 0.5f);
										} else if (interpolatedTime > 0.5) {
											pip.channel_pop_iv3
													.setAlpha((interpolatedTime - 0.5f) / 0.5f);
										}
									}
									if (flag3 & interpolatedTime > 0.5f) {
										pip.channel_pop_iv3.setImageBitmap(bms
												.get(0));// 翻转后的新图
										flag3 = false;
									}
								}
							});
					pip.channel_pop_iv3.clearAnimation();
					pip.channel_pop_iv3.startAnimation(anim3);
				}
			}, 1000);
		}

	}

	@Override
	public void setPopState(boolean b) {
		// TODO Auto-generated method stub

	}
}
